// locutor command line client
// (c) 2009, Normen Müller, normen.mueller@gmail.com  
// $Id: GrGen.scala 86 2010-05-11 21:32:13Z normen.mueller $
package locutor

import java.io.File

import scaup.Views._
import scaup.io.{Process => process}

import locutor.rws.RewriteSystem
import locutor.rws.rs.Rule
import locutor.rws.rs.RuleSystem
import locutor.rws.gm.GraphModel
import locutor.g.DependencyGraph
import locutor.g.ImpactGraph

/** Interface to GrGen.
 * 
 *  @author <a href="mailto:normen.mueller@googlemail.com">Normen M&#xFC;ller</a>
 *  @version 0.0.4
 * 
 *  @todo use GrGen to generate model and action DLLs
 */
object GrGen {  
  private val tmp = System.getProperty("locutor.tmp").toFile
  
  //private val gen = System.getProperty("locutor.grgen") + "/GrGen "
  
  private val shl = System.getProperty("locutor.grgen") + "/GrShell -N "
  
  private val conf =
    "debug set layout Hierarchic" ::
    "dump set edge only dependsOn  color Orange" ::
    "dump set edge only affectedBy color Red" ::
    "dump set edge only childOf    color LightGrey" ::
    "dump set edge only childOf labels off" :: Nil
  
  //@todo get rid of name parameter
  private [locutor] def markup(name: String, dependencyGraph: DependencyGraph, rewriteSystem: RewriteSystem) = DependencyGraph.parse(
    exec(flush(flush(name, rewriteSystem), dependencyGraph, conf, "xgrs <annotate & interlink>", List("export "+ (tmp/(name + "-sem.grs")).path + " withvariables","exit")))
  )
  
  //@todo get rid of name parameter
  private [locutor] def markup(name: String, impactGraph: ImpactGraph, rewriteSystem: RewriteSystem) = ImpactGraph.parse(
    exec(flush(flush(name, rewriteSystem), impactGraph, conf, "xgrs ripple", List("export "+ (tmp/(name + "-imp.grs")).path + " withvariables","exit")))
  )
  
  private def exec(file: File) = process(shl + file.name, tmp).waitFor match {
    case 0 => ((g: File) => if(g exists) g else error("Fatal error during graph rewriting."))(tmp / (file.label + "-sem.grs"))
    case _ => error("Fatal error GrGen initialization.")
  }
  
  private def flush(name: String, rewriteSystem: RewriteSystem) =
    (rewriteSystem.ruleSystem.toGrGen >>> (tmp / ((rewriteSystem.graphModel.toGrGen >>> (tmp / (name + ".gm"))).label + ".grg"))).label    
  
  private def flush(name: String, dependencyGraph: DependencyGraph, conf: List[String], xgrs: String, cmds: List[String]) =
    ( ("new graph " + name)
    + dependencyGraph.toGrShell
    + (conf mkString ("\n", "\n", "\n"))
    + xgrs
    + (cmds mkString ("\n", "\n", "\n"))
    ) >>> (tmp / (name + ".grs"))  
}
